package com.example.administrator.soundinputdemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageButton;

import com.baidu.aip.asrwakeup3.core.recog.MyRecognizer;
import com.baidu.speech.EventListener;
import com.baidu.speech.asr.SpeechConstant;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements EventListener {
    private static final String TAG = "SoundRegActivity";
    private WebView webview;
    private ImageButton btnRecord;
    MyRecognizer myRecognizer;

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化界面
        webview = findViewById(R.id.my_webview);
        webview.requestFocus();
        btnRecord = findViewById(R.id.btn_sound_input);
        webview.loadUrl("http://106.12.30.77:8082/index.html");
        WebSettings webSettings = webview.getSettings();
        webview.addJavascriptInterface(this, "nativeMethod");
        webSettings.setJavaScriptEnabled(true);

        myRecognizer = new MyRecognizer(this, this);

        btnRecord.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                Log.e(TAG, "onTouch: " );
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    //TODO 打开语音识别器
                    Map<String,Object> params = new HashMap<>();
                    params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);
                    myRecognizer.start(params);
                    // TODO 结束
                }
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    //TODO 关闭语音识别器
                    myRecognizer.stop();
                    //TODO 结束
                }
                return false;
            }
        });

    }


    @Override
    public void onEvent(String name, String result, byte[] data, int offset, int length) {

        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {
            Log.e(TAG, "onEvent: " + result);
            String bestResult = "";
            //TODO 开始 将params中返回的文字信息解析，并保存到bestResult中
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(result);
                //if (jsonObject.getString("result_type").equals("final_result")) {
                bestResult = jsonObject.getString("best_result");
                //}
            } catch (JSONException e) {
                e.printStackTrace();
            }


            //TODO 结束
            if (!bestResult.isEmpty()) {
                //调用HTML5页面上的js方法send（）完成留言信息的提交
                webview.loadUrl("javascript:send('" + bestResult + "')");
            }
        }
    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    private void initPermission() {
        String permissions[] = {Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                // 进入到这里代表没有权限.

            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // 此处为android 6.0以上动态授权的回调，用户自行实现。
    }

}
//